package cn.rulian.demo.hello.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.vo.Result;
import cn.rulian.demo.hello.bo.Full;
import cn.rulian.demo.hello.service.FullService;
import cn.rulian.demo.hello.vo.FullVo;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;

/**
 * 全面示例 Controller
 */

@Controller
@RequestMapping("/demo/hello/full")
public class FullController {
	
	@Autowired
	private FullService service;
	
	private final String path="demo/hello/full_"; //页面基本路径

	/**
	 * 页面基本路径
	 */
	private String getPath()
	{
		return path;
	}
	
	/**
	 * 列表页面
	 */
	@RequestMapping("/listPage")
	public String listPage() {
		return this.getPath()+"list";
	}

	/**
	 * 查询
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Result listData(FullVo vo) {
		return service.query(vo);
	}

	/**
	 * 增加页面
	 */
	@RequestMapping("/addPage")
	public String addPage() {
		return this.getPath()+"add";
	}

	/**
	 * 增加
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Message add(FullVo vo) {
		Message rm = new Message();
		Full bo = vo.getObj();
		try {
			
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 修改页面
	 */
	@RequestMapping("/updatePage")
	public String updatePage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"update";
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Message update(FullVo vo,Long id) {
		Message rm = new Message();
		try {
			Full obj = vo.getObj();
			Full bo = service.findOne(id);

			bo.setCode(obj.getCode());
			bo.setName(obj.getName());
			bo.setCity(obj.getCity());
			bo.setCourse(obj.getCourse());
			bo.setTea(obj.getTea());
			bo.setHobby(obj.getHobby());
			bo.setFullSort(obj.getFullSort());
			bo.setMySort(obj.getMySort());
			bo.setBoolean1(obj.getBoolean1());
			bo.setBoolean2(obj.getBoolean2());
			bo.setIntNum1(obj.getIntNum1());
			bo.setIntNum2(obj.getIntNum2());
			bo.setDoubleNum1(obj.getDoubleNum1());
			bo.setDoubleNum2(obj.getDoubleNum2());
			bo.setTheDate1(obj.getTheDate1());
			bo.setTheDate2(obj.getTheDate2());
			bo.setTheTime1(obj.getTheTime1());
			bo.setTheTime2(obj.getTheTime2());
			bo.setRemark(obj.getRemark());
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Message delete(Long ids[]) {
		Message rm = new Message();
		try {
			for(Long id:ids)
			{
				service.delete(id);
			}
			
			rm.setMsg("删除成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("删除失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping("/detailPage")
	public String detailPage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"detail";
	}
	

	/**
	 * 导出Excel
	 * @throws Exception 
	 */
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response, FullVo vo) throws Exception {
		
		String bookName = "全面示例"; //文件名
		
		File file = File.createTempFile("Export", "xls"); //创建临时文件
		jxl.write.WritableWorkbook book = Workbook.createWorkbook(file); //工作薄
		jxl.write.WritableSheet sheet = book.createSheet("Sheet1", 0); //工作表
		
		//通用设置
		sheet.getSettings().setDefaultRowHeight(400); //空白行高度
		sheet.getSettings().setDefaultColumnWidth(12); //默认列宽
		sheet.setColumnView(0, 8);//第1列 宽度（序号）
		
		//输出标题
		{
			String title = "全面示例数据"; //标题
			int lieNum = 20; //总列数（标题跨列用）
			
			//标题行高
			sheet.setRowView(0, 700); //第1行
			
			//标题样式
			WritableCellFormat formatterTitle= new WritableCellFormat(); 
			formatterTitle.setAlignment(Alignment.CENTRE);//水平对齐
			formatterTitle.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直对齐
			WritableFont font = new WritableFont(WritableFont.TAHOMA, 18, WritableFont.BOLD, false); //字体
			formatterTitle.setFont(font);

			//输出标题
			sheet.mergeCells(0, 0, lieNum-1, 0); //合并单元格
			sheet.addCell(creatLabel(0,0,formatterTitle,title)); //输出标题
		}
		
		//行列号
		int rowNum = 1; //行号
		int columnNum = 0; //列号

		//输出列标题
		{
			//列标题 行高
			sheet.setRowView(1, 500);//第2行
			
			//列标题样式
			WritableCellFormat formatterColumnTitle= new WritableCellFormat(); //列标题样式
			formatterColumnTitle.setAlignment(Alignment.CENTRE);//水平对齐
			formatterColumnTitle.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直对齐
			formatterColumnTitle .setBackground(Colour.GRAY_25);//背景色
			formatterColumnTitle.setBorder(Border.ALL, BorderLineStyle.THIN);//边框线  所有边框 细线
			
			//列标题
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "序号"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "编号"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "名称"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "城市"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "课程"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "茶品"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "爱好"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "Full分类"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "我的分类"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "布尔1"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "布尔2"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "整数"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "整数2"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "实数"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "实数2"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "日期"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "日期2"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "时间"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "时间2"));
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "增加时间"));
		}
		
		//输出内容
		List<Full> list = service.QueryExcelData(vo); //输出数据
		if(list != null && list.size() > 0)
		{
			SimpleDateFormat formatterDate = new SimpleDateFormat("yyyy-MM-dd"); //日期格式化
			SimpleDateFormat formatterTime = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //时间格式化
			
			//内容样式
			WritableCellFormat formatterCon= new WritableCellFormat(); //内容样式
			formatterCon.setAlignment(Alignment.CENTRE);//水平对齐
			formatterCon.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直对齐
			formatterCon.setBorder(Border.ALL, BorderLineStyle.THIN);//边框线  所有边框 细线
			
			//定义变量
			String codeStr = ""; // 编号
			String nameStr = ""; // 名称
			String cityStr = ""; // 城市
			String courseStr = ""; // 课程
			String teaStr = ""; // 茶品
			String hobbyStr = ""; // 爱好
			String fullSortStr = ""; // Full分类
			String mySortStr = ""; // 我的分类
			String boolean1Str = ""; // 布尔1
			String boolean2Str = ""; // 布尔2
			String intNum1Str = ""; // 整数
			String intNum2Str = ""; // 整数2
			String doubleNum1Str = ""; // 实数
			String doubleNum2Str = ""; // 实数2
			String theDate1Str = ""; // 日期
			String theDate2Str = ""; // 日期2
			String theTime1Str = ""; // 时间
			String theTime2Str = ""; // 时间2
			String addTimeStr = ""; // 增加时间
			
			for(int i = 0; i < list.size(); i++)
	    	{
				rowNum++;
				columnNum=0;

				sheet.setRowView(rowNum, 400); //行高
				
				//初始化变量
				codeStr = ""; // 编号
				nameStr = ""; // 名称
				cityStr = ""; // 城市
				courseStr = ""; // 课程
				teaStr = ""; // 茶品
				hobbyStr = ""; // 爱好
				fullSortStr = ""; // Full分类
				mySortStr = ""; // 我的分类
				boolean1Str = ""; // 布尔1
				boolean2Str = ""; // 布尔2
				intNum1Str = ""; // 整数
				intNum2Str = ""; // 整数2
				doubleNum1Str = ""; // 实数
				doubleNum2Str = ""; // 实数2
				theDate1Str = ""; // 日期
				theDate2Str = ""; // 日期2
				theTime1Str = ""; // 时间
				theTime2Str = ""; // 时间2
				addTimeStr = ""; // 增加时间
				
				//变量赋值
				Full bo = list.get(i); 
				if(bo.getCode() != null){	codeStr = bo.getCode().toString();	} //编号
				if(bo.getName() != null){	nameStr = bo.getName().toString();	} //名称
				if(bo.getCity() != null){	cityStr = bo.getCity().toString();	} //城市
				if(bo.getCourse() != null){	courseStr = bo.getCourse().toString();	} //课程
				if(bo.getTea() != null){	teaStr = bo.getTea().toString();	} //茶品
				if(bo.getHobby() != null){	hobbyStr = bo.getHobby().toString();	} //爱好
				if(bo.getFullSort() != null){	fullSortStr = bo.getFullSort().getName();	} //Full分类
				if(bo.getMySort() != null){	mySortStr = bo.getMySort().getName();	} //我的分类
				if(bo.getBoolean1() != null){	boolean1Str = bo.getBoolean1()?"开":"关";		} //布尔1
				if(bo.getBoolean2() != null){	boolean2Str = bo.getBoolean2()?"开":"关";		} //布尔2
				if(bo.getIntNum1() != null){	intNum1Str = bo.getIntNum1().toString();	} //整数
				if(bo.getIntNum2() != null){	intNum2Str = bo.getIntNum2().toString();	} //整数2
				if(bo.getDoubleNum1() != null){	doubleNum1Str = bo.getDoubleNum1().toString();	} //实数
				if(bo.getDoubleNum2() != null){	doubleNum2Str = bo.getDoubleNum2().toString();	} //实数2
				if(bo.getTheDate1() != null){	theDate1Str = formatterDate.format(bo.getTheDate1());	} //日期
				if(bo.getTheDate2() != null){	theDate2Str = formatterDate.format(bo.getTheDate2());	} //日期2
				if(bo.getTheTime1() != null){	theTime1Str = formatterTime.format(bo.getTheTime1());	} //时间
				if(bo.getTheTime2() != null){	theTime2Str = formatterTime.format(bo.getTheTime2());	} //时间2
				if(bo.getAddTime() != null){	addTimeStr = formatterTime.format(bo.getAddTime());	} //增加时间
				
				//输出一行数据
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, (i+1)+"")); 
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, codeStr )); // 编号
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, nameStr )); // 名称
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, cityStr )); // 城市
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, courseStr )); // 课程
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, teaStr )); // 茶品
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, hobbyStr )); // 爱好
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, fullSortStr )); // Full分类
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, mySortStr )); // 我的分类
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, boolean1Str )); // 布尔1
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, boolean2Str )); // 布尔2
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, intNum1Str )); // 整数
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, intNum2Str )); // 整数2
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, doubleNum1Str )); // 实数
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, doubleNum2Str )); // 实数2
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, theDate1Str )); // 日期
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, theDate2Str )); // 日期2
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, theTime1Str )); // 时间
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, theTime2Str )); // 时间2
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, addTimeStr )); // 增加时间
	    	}
		}

		book.write();
		book.close();
		
		//-------------------------------

		FileInputStream f = new FileInputStream(file);
		byte[] fb = new byte[f.available()];
		f.read(fb);
		response.setHeader("Content-disposition", "attachment; filename=" + new String((bookName + ".xls").getBytes("gb2312"), "iso8859-1"));
		ByteArrayInputStream bais = new ByteArrayInputStream(fb);
		int b;
		while ((b = bais.read()) != -1)
		{
			response.getOutputStream().write(b);
		}
		response.getOutputStream().flush();
		f.close();
	}
	
	private Label creatLabel(int rowNum, int columnNum, WritableCellFormat formatter, String con) //行，列，样式，内容 
	{  
		 return new Label(columnNum, rowNum, con,formatter);   
	}  
	
	
}
